from odoo import models, api
from odoo.addons.base.tests.test_uninstall import environment
from odoo.exceptions import UserError


class SbMESPartner(models.Model):
    _inherit = 'res.partner'

    def cron_all(self):
        domain = [('code', '!=', False), ('is_company', '=', True)]
        records = self.env['res.partner'].sudo().search(domain)
        for rec in records:
            rec.partner_upload_mes()

    @api.model_create_multi
    def create(self, vals_list):
        result = super().create(vals_list)
        mes_enabled = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.enabled')], limit=1).s_value
        if mes_enabled:
            for rec in result:
                if rec.is_company and rec.code:
                    rec.with_delay().partner_upload_mes()
        return result

    def write(self, vals):
        res = super().write(vals)
        mes_enabled = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.enabled')], limit=1).s_value
        if mes_enabled:
            for record in self:
                if record.is_company and record.code:
                    record.with_delay().partner_upload_mes()
        return res

    def partner_upload_mes(self):
        """
        客户供应商
        """
        # partner_type = self.env.context.get('type')
        if self.supplier_rank > 0:
            supplier_list = []
            for supplier in self:
                # 联系人
                bs_sup_dt = []
                for sup in supplier.child_ids:
                    bs_sup_dt.append({
                        "contacts_user": sup.name or '',  # 联系人
                        "contacts_phone": sup.mobile or '',  # 联系电话
                        "contacts_fax": "",  # 传真
                        "contacts_email": sup.email or '',  # 邮件地址
                        "contacts_addr": "",  # 联系地址
                        "is_valid": "Y",  # 启用状态
                        "remark": "0"
                    })
                # 供应商产品
                bs_sup_mtrltf = []
                domain = [('partner_id', '=', supplier.id), ("product_tmpl_id.active", "=", True)]
                sup_price = self.env['product.supplierinfo'].sudo().search(domain)
                for supp in sup_price:
                    bs_sup_mtrltf.append({
                        "sup_mtrl_code": supplier.code,  # 供应商物料编码
                        "mtrl_code": supp.product_tmpl_id.default_code,  # 物料编码
                        "sup_mtrlver": "",  # 供应商物料版本号
                        "sup_bd": "",  # 供应商BD码
                        "barcode_prefix": "",  # 前缀标识
                        "pack_qty": supp.min_qty,  # 最小包装数
                    })
                supplier_list.append({
                    "cust_code": supplier.code if supplier.code else supplier.id,
                    "sup_code": supplier.code,
                    "sup_name": supplier.name,
                    "erp_sup_code": supplier.code,
                    "qrcode_code": "",
                    "country_code": supplier.country_id.code or '',
                    "authe_state": 0,  # 认证状态
                    "authe_man": "",  # 认证人
                    "authe_date": "",  # 认证时间
                    "legal_person": "",  # 法人
                    "tel_no": supplier.mobile or '',  # 电话
                    "web_addr": supplier.website or '',  # 网址
                    "ent_nature": "",  # 企业性质
                    "bus_scope": "",  # 经营范围
                    "est_date": "",  # 成立时间
                    "reg_capital": 0,  # 注册资金
                    "emp_nums": 0,  # 员工人数
                    "sup_addr": "0",  # 地址
                    "is_valid": "Y",  # 启用状态
                    "remark": "0",  # 备注
                    "supplier": "Y",  # 物料供应商
                    "out_supplier": "N",  # 制程外包物料供应商
                    "bs_sup_dt": bs_sup_dt,
                    "bs_sup_mtrltf": bs_sup_mtrltf
                })
            data = {
                "docType": "BS_SUP",
                "updateType": "UPDATE",
                "data": supplier_list
            }
            self.env['s.mes.upload'].upload_data(data)
        elif not self.is_virtual_customer and self.supplier_rank <= 0:
            customer_list = []
            for customer in self:
                customer_list.append({
                    "cust_code": customer.code if customer.code else customer.id,
                    "cust_name": customer.name,
                    "erp_cust_code": customer.code,
                    "fifo_rule": 0,  # 出库规则 0:默认 1:FIFO 2:LIFO 3:不管控
                    "fifo_a": 0,  # A材FIFO粒度
                    "fifo_b": 0,  # B材FIFO粒度
                    "fifo_c": 0,  # C材FIFO粒度
                    "is_valid": "Y",  # 启用状态 N:未启用 Y:已启用
                    "is_coc": "N",  # 出货报告 <= 1 字符
                    "coc_type": 1,  # 报告类型 1:批次 2:周期
                    "remark": "0"  # 备注
                })
            data = {
                "docType": "BS_CUST",
                "updateType": "UPDATE",
                "data": customer_list
            }
            self.env['s.mes.upload'].upload_data(data)
        else:
            print('发送失败')
